package com.xiehua.task.server.handler;

import com.xiehua.task.intf.AbsBusinessHandler;
import com.xiehua.task.job.TaskReverseDefualt;
import com.xiehua.task.job.pool.DelayJob;
import com.xiehua.task.job.pool.FixedJob;
import com.xiehua.task.job.pool.Job;
import com.xiehua.task.msg.TaskRegReqBody;
import com.xiehua.task.msg.TaskRegRespBody;
import com.xiehua.task.prop.XiehuaConfig;
import com.xiehua.task.protocol.Type;
import com.xiehua.task.protocol.TaskPacket;
import com.xiehua.task.redis.RedisTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tio.core.Aio;
import org.tio.core.ChannelContext;
import org.tio.utils.json.Json;

import java.util.concurrent.atomic.AtomicLong;

import static com.xiehua.task.job.pool.Job.JobType.delay;
import static com.xiehua.task.job.pool.Job.JobType.fixed;

/**
 * @author Mr.zhang
 * 2018年3月27日 下午9:51:28
 */
public class TaskRegReqHandler extends AbsBusinessHandler<TaskRegReqBody> {

	private static Logger log = LoggerFactory.getLogger(TaskRegReqHandler.class);


	public static final String TASK_ID = "task_id";

	AtomicLong tokenSeq = new AtomicLong();

	/**
	 *
	 * @author tanyaowu
	 */
	public TaskRegReqHandler() {
	}

	/**
	 * @return
	 * @author tanyaowu
	 */
	@Override
	public Class<TaskRegReqBody> bodyClass() {
		return TaskRegReqBody.class;
	}

	/**
	 * @param packet
	 * @param bsBody
	 * @param channelContext
	 * @return
	 * @throws Exception
	 * @author tanyaowu
	 */
	@Override
	public Object handler(TaskPacket packet, TaskRegReqBody bsBody, ChannelContext channelContext) throws Exception {
		log.info("收到Task注册请求消息:{}", bsBody.toString());
		Job job = null;
		//add delay job
		TaskReverseDefualt reverseDefualt = new TaskReverseDefualt(RedisTemplate.getJedis());
		if(delay.equals(bsBody.getType())) job = reverseDefualt.delay(Json.toBean(bsBody.getJobContent(), DelayJob.class), channelContext.getGroupContext());
		if(fixed.equals(bsBody.getType())) job = reverseDefualt.delay(Json.toBean(bsBody.getJobContent(), FixedJob.class), channelContext.getGroupContext());
		reverseDefualt.clear();
		if(job == null) return null;
		//build resp
		TaskRegRespBody loginRespBody = new TaskRegRespBody();
		loginRespBody.setSuccess(true);
		loginRespBody.setTaskId(job.getJobId());
		loginRespBody.setRegTaskReqId(job.getReqId());
		//resp packet
		TaskPacket respPacket = new TaskPacket(Type.TASK_REG_RESP,packet.getClientId());
		String bizData = Json.toJson(loginRespBody);
		respPacket.setBody(bizData.getBytes(TaskPacket.CHARSET));
		respPacket.signData(bizData, XiehuaConfig.getInstance().get(packet.getClientId()));
		//返回消息
		Aio.send(channelContext,respPacket);
		return null;
	}

	private String newToken() {
		return System.currentTimeMillis() + "_" + tokenSeq.incrementAndGet();
	}

}
